package com.ithinks.flow.common.utils.protocol.socket.aio.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * @Description
 * @ClassName AioReaderHandler
 * @Author MR.LI
 * @date 2020.12.07 18:04
 */
public class AioReaderHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel channel;

    //只能有一个线程去操作这个变量，任何线程调用这个对象得await方法，都会发生阻塞，直到这个变量清0为止。
    private CountDownLatch latch;

    public AioReaderHandler(AsynchronousSocketChannel channel, CountDownLatch latch){

        this.channel = channel;
        this.latch = latch;
    }
    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        buffer.flip();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        String msg;
        try {
            msg = new String(bytes,"UTF-8");
            System.out.println("accept message:"+msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.err.println("数据读取失败。。。。");
        try {
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }
}
